//
//  NewFeatureCollectionViewController.swift
//  CBWWeiBo
//
//  Created by 陈博文 on 16/1/11.
//  Copyright © 2016年 陈博文. All rights reserved.
//

import UIKit
import SnapKit


private let reuseIdentifier = "newFeature"

class NewFeatureCollectionViewController: UICollectionViewController {
    
    @IBOutlet weak var flowLayout: NewFeatureFlowLayout!
    
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    /// 新特性总页数
    private var maxPageCount = 4

}

extension NewFeatureCollectionViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return 4
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell
        if (indexPath.item % 2 == 1){
            cell.backgroundColor = UIColor.redColor()}else{
            cell.backgroundColor = UIColor.grayColor()
        }
        
        cell.index = indexPath.item
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
        // 1.获取当前显示的cell对应的索引
        guard let path = collectionView.indexPathsForVisibleItems().last else
        {
            return
        }
        
        // 2.获取当前索引对应的cell
        guard let cell = collectionView.cellForItemAtIndexPath(path) as? CollectionViewCell else
        {
            return
        }
        
        //        XMGLog(path.item)
        // 2.判断是否是最后一页
        //        cell.startButton.hidden = true // 有bug
        if path.item == maxPageCount - 1
        {
            CBWLog("最后一页")
            /*
            cell.startButton.hidden = false
            
            cell.startButton.transform = CGAffineTransformMakeScale(0.0, 0.0)
            /*
            第一个参数: 动画时长
            第二个参数: 延迟时长
            第三个参数: 震动幅度 0.0~1.0之间, 值越小震动越厉害
            第四个参数: 动画初始速度, 值越大开始就越快
            第五个参数: 附加选项
            第六个参数: 需要执行动画代码
            第七个参数: 动画执行完毕之后的回调
            */
            UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            cell.startButton.transform = CGAffineTransformIdentity
            }, completion: { (_) -> Void in
            XMGLog("动画执行完毕")
            })
            */
            cell.startButtonAnimation()
        }
     }
    
}


class CollectionViewCell:UICollectionViewCell {
    
    /// 图片索引
    var index: Int = 0
        {
        didSet
        {
            iconImageView.image = UIImage(named: "new_feature_\(index + 1)")
            // 2.判断是否是最后一页
            startButton.hidden = true
        }
    }

    // 通过代码创建调用
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    // 通过xib/sb创建调用
    required init?(coder aDecoder: NSCoder) {
        // fatalError: 致命错误, 只要执行该代码就会崩溃
        // 用意: 让我们编写更简单高效代码
        //        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        setup()
    }

    
    private func setup(){
        
        contentView.addSubview(iconImageView)
        contentView.addSubview(startButton)
               iconImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(0)
        }
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView.snp_bottom).offset(-160)
        }
    }
    
    // MARK:=============== lazy ===============
    
    private lazy var iconImageView:UIImageView = {
        return UIImageView()
        
    }()
    
    private  lazy var startButton :UIButton  = {
        
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "new_feature_button"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_button_highlighted"), forState: .Highlighted)
        
        btn.addTarget(self, action: "startButtonClick", forControlEvents: .TouchUpInside)
        btn.sizeToFit()
        return btn

    }()
    // MARK:- 外部控制方法
    func startButtonAnimation()
    {
        startButton.hidden = false
        startButton.userInteractionEnabled = false
        startButton.transform = CGAffineTransformMakeScale(0.0, 0.0)
        /*
        第一个参数: 动画时长
        第二个参数: 延迟时长
        第三个参数: 震动幅度 0.0~1.0之间, 值越小震动越厉害
        第四个参数: 动画初始速度, 值越大开始就越快
        第五个参数: 附加选项
        第六个参数: 需要执行动画代码
        第七个参数: 动画执行完毕之后的回调
        */
        UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }, completion: { (_) -> Void in
//                CBWLog("动画执行完毕")
                self.startButton.userInteractionEnabled = true
        })
    }
    
  @objc  private func startButtonClick(){
//    print("----buttonClick------")
        NSNotificationCenter.defaultCenter().postNotificationName(CBWChangeRootViewControllerNotification, object: self, userInfo: ["message": true])
    }

}

class NewFeatureFlowLayout:UICollectionViewFlowLayout {
    
    override func prepareLayout() {
        
        minimumInteritemSpacing = 0
        minimumLineSpacing      = 0
        scrollDirection         = .Horizontal
        
        itemSize = UIScreen.mainScreen().bounds.size
        
        self.collectionView?.showsHorizontalScrollIndicator = false
        self.collectionView?.showsVerticalScrollIndicator   = false
        self.collectionView?.pagingEnabled                  = true
        self.collectionView?.bounces                        = false
    }
   
   }
